﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */

using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;

namespace SharePointHelper.DLL.SSOM
{
	public class Web
	{
        #region 获取当前 SPWeb
        /// <summary>
        /// 获取当前 SPWeb
        /// 不要 DISPOSE!!!!
        /// </summary>
        /// <returns></returns>
        public static SPWeb GetWeb()
		{
			SPWeb web = null;
			try
			{
				// 初始化
				if (SPContext.Current == null) { throw new Exception("SPContext is null"); }
				if (SPContext.Current.Web == null) { throw new Exception("Failed to get SPWeb from the SPContext object"); }

				web = SPContext.Current.Web;
			}
			catch (Exception ex)
			{
				web = null;
			}
			return web;
		}
        #endregion

        #region 根据相对路径以及所给的site collection来获取SPWeb
        /// <summary>
        /// 根据相对路径以及所给的site collection来获取SPWeb
        /// </summary>
        /// <param name="site"></param>
        /// <param name="url">"/" = root web for current site collection</param>
        /// <returns></returns>
        public static SPWeb GetWeb(SPSite site, string url)
		{
			SPWeb web = null;
			try
			{
				// 初始化
				if (site == null) { site = Site.GetSite(); }
				if (site == null) { throw new Exception("Failed to get SPSite from SPContext"); }
				
				// 格式化 url, making it relative
				url = Utilities.ConvertAbsoluteUrlToRelativeUrl(url);

				// 打开 web
				web = site.OpenWeb(url);
				if (web == null) { throw new Exception("Failed to open SPWeb using relative url: " + url); }
			}
			catch (Exception ex)
			{
				Log.WriteError("dyu6fukcgfhygugovhb", ex, "relativeUrl: " + url);
				web = null;
			}
			return web;
		}
        #endregion

        #region 根据相对路径来获取当前site collection中的SPWeb
        /// <summary>
        /// 根据相对路径来获取当前site collection中的SPWeb
        /// </summary>
        /// <param name="url">"/" = root web for current site collection</param>
        /// <returns></returns>
        public static SPWeb GetWeb(string url)
		{
			SPWeb web = null;
			try
			{
				web = GetWeb(null, url);
			}
			catch (Exception ex)
			{
				Log.WriteError("67rigfykdffty", ex, "relativeUrl: " + url);
				web = null;
			}
			return web;
		}
        #endregion

        #region 从 Feature的 SPFeatureReceiverProperties中获取SPWeb
        /// <summary>
        /// 从 Feature的 SPFeatureReceiverProperties中获取SPWeb
        /// </summary>
        /// <param name="properties"></param>
        /// <returns></returns>
        public static SPWeb GetWeb(SPFeatureReceiverProperties properties)
		{
			SPWeb web = null;
			try
			{
				// 初始化
				if (properties == null) { throw new Exception("SPFeatureReceiverProperties passed is null"); }

				try
				{
					web = properties.Feature.Parent as SPWeb;
				}
				catch (Exception ex)
				{
					throw new Exception("Failed to cast SPFeatureReceiverProperties to an SPWeb. Most likely the feature is NOT scoped to Web: " + ex.Message);
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("dt7idt7tfxdfdrdt", ex);
				web = null;
			}
			return web;
		}
        #endregion

        #region 根据Id获取SPWeb
        /// <summary>
        /// 根据Id获取SPWeb
        /// </summary>
        /// <param name="webId"></param>
        /// <param name="site"></param>
        /// <returns></returns>
        public static SPWeb GetWeb(Guid webId, SPSite site)
		{
			SPWeb web = null;
			try
			{
				// 初始化
				if (webId == null || webId == Guid.Empty) { throw new Exception("Null or empty guid passed for webId"); }
				if (site == null) { site = Site.GetSite(); }
				if (site == null) { throw new Exception("Failed to get SPSite from SPContext"); }


				web = site.AllWebs[webId];
				if (web == null)
				{
					throw new Exception("Failed to find SPWeb in site: " + site.PortalName
						+ " using webId: " + webId);
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("8i67ru6yew54tdsgxd", ex, "webId: " + webId);
				web = null;
			}
			return web;
		}
        #endregion

        #region 设置某个web的 Master page template
        /// <summary>
        /// 设置某个web的 Master page template
        /// </summary>
        /// <param name="web"></param>
        /// <param name="publishingPagesMasterFilename"></param>
        /// <param name="nonPublishingPagesMasterFilename"></param>
        public static bool SetMaster(SPWeb web, string publishingPagesMasterFilename, string nonPublishingPagesMasterFilename)
		{
			bool isSuccess = false;
			try
			{
				// 初始化
				if (web == null) { throw new Exception("SPWeb passed is null"); }
				if (string.IsNullOrEmpty(publishingPagesMasterFilename) && string.IsNullOrEmpty(nonPublishingPagesMasterFilename)) 
				{ 
					throw new Exception("Publishing master and Non Publishing master cannot both be null"); 
				}


				// 创建 master urls
				Uri publishingPagesMasterUri = null;
				if (!string.IsNullOrEmpty(publishingPagesMasterFilename) && PublishingWeb.IsPublishingWeb(web))
				{
					publishingPagesMasterUri = new Uri(web.Site.Url + "/_catalogs/masterpage/" 
						+ publishingPagesMasterFilename);
				}
				Uri nonPublishingPagesMasterUri = null;
				if (!string.IsNullOrEmpty(nonPublishingPagesMasterFilename))
				{
					nonPublishingPagesMasterUri = new Uri(web.Site.Url + "/_catalogs/masterpage/" 
						+ nonPublishingPagesMasterFilename);
				}

				if (publishingPagesMasterUri != null)
				{
					// master page used by all publishing pages on the site
					web.CustomMasterUrl = publishingPagesMasterUri.AbsolutePath;
				}

				if (nonPublishingPagesMasterUri != null)
				{
					// master page used by all forms and pages on the site NOT publishing pages
					web.MasterUrl = nonPublishingPagesMasterUri.AbsolutePath;
				}
				web.Update();
				isSuccess = true;
			}
			catch (Exception ex)
			{
				Log.WriteError("7i6ro87tje6rhegdsgdfs", ex, "publishing master: " + publishingPagesMasterFilename
					+ ", non publishing master: " + nonPublishingPagesMasterFilename);
				isSuccess = false;
			}
			return isSuccess;
		}

        /// <summary>
        /// 设置某个web的 Master page template
        /// 应用 template 到  publishing and non publishing pages
        /// </summary>
        /// <param name="web"></param>
        /// <param name="masterPageFilename"></param>
        /// <returns></returns>
        public static bool SetMaster(SPWeb web, string masterPageFilename)
		{
			return SetMaster(web, masterPageFilename, masterPageFilename);
		}
        #endregion

        #region 获取 web url
        /// <summary>
        /// 获取 web url, 末尾没有斜线 (除非 root)
        /// </summary>
        /// <param name="web"></param>
        /// <param name="isAbsoluteUrl"></param>
        /// <returns></returns>
        public static string GetUrl(SPWeb web, bool isAbsoluteUrl)
		{
			string url = null;
			if (web != null)
			{
				// 获取 url from 
				if (!isAbsoluteUrl) { url = web.ServerRelativeUrl; } else { url = web.Url; }

				// 移除尾部斜线
				if (url != null && url.Length > 1 && url.Substring(url.Length - 1) == "/")
				{
					url = url.Substring(0, url.Length - 1);
				}
			}
			return url;
		}
        /// <summary>
        /// 获取web的相对url, 末尾没有斜线 (除非 root)
        /// </summary>
        /// <param name="web"></param>
        /// <returns></returns>
        public static string GetUrl(SPWeb web)
		{
			return GetUrl(web, false);
		}
        #endregion

        #region 根据url获取SPWeb
        /// <summary>
        /// 根据url获取SPWeb
        /// http://chrisdomino.com/blog/post/A-Nifty-SharePoint-Utility-to-Get-Web-List-and-List-Item-Ids-from-a-URL
        /// </summary>
        public static SPWeb GetWebByUrl(string url, SPSite site)
		{
			SPWeb web = null;
			string originalUrl = url;
			try
			{
				// 初始化
				if (string.IsNullOrEmpty(url)) { throw new Exception("Url passed is null"); }
				if (site == null) { site = Site.GetSite(); }
				if (site == null) { throw new Exception("Failed to get SPSite from SPContext"); }
				string listUrlSegment = null;


				// 转化成相对路径
				if (!Utilities.IsAbsoluteUrl(url)) { url = Utilities.ConvertRelativeUrlToAbsoluteUrl(url, site); }

				while (url.IndexOf("/") != -1)
				{
					web = site.AllWebs.Where(w => w.Url.Equals(url, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
					if (web != null) { break; }
					else
					{
						listUrlSegment = url.Substring(url.LastIndexOf("/"));
						url = url.Substring(0, url.LastIndexOf("/"));
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("e658t776564esrdfd", ex, "url: " + originalUrl);
				web = null;
			}
			return web;
		}

        /// <summary>
        /// 根据url获取SPWeb
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static SPWeb GetWebByUrl(string url)
		{
			return GetWebByUrl(url, Site.GetSite());
		}
        #endregion
    }
}
